import { BaseStore } from './BaseStore.js';

/**
 * SessionStorage 封装类
 * 提供对 sessionStorage 的统一操作接口
 */
class SessionStore extends BaseStore {
  constructor(prefix = 'app') {
    super(prefix);
    this.storage = window.sessionStorage;
    this.available = this.checkAvailability();
    this.isAsync = false; // SessionStorage 是同步的
  }

  /**
   * 检查 sessionStorage 是否可用
   * @returns {boolean} 是否可用
   */
  isAvailable() {
    try {
      const test = '__sessionStorage_test__';
      sessionStorage.setItem(test, test);
      sessionStorage.removeItem(test);
      return true;
    } catch (error) {
      console.warn('sessionStorage is not available:', error);
      return false;
    }
  }

  /**
   * 设置值到 sessionStorage
   * @param {string} key 键名
   * @param {any} value 值
   * @param {Object} options 选项 (暂时保留，用于未来扩展)
   */
  set(key, value, options = {}) {
    if (!this.storage) {
      console.warn('sessionStorage is not available');
      return false;
    }

    try {
      const serializedValue = this.serialize(value);
      const storageKey = this.getKey(key);
      this.storage.setItem(storageKey, serializedValue);
      return true;
    } catch (error) {
      console.error('Failed to set sessionStorage item:', error);
      return false;
    }
  }

  /**
   * 从 sessionStorage 获取值
   * @param {string} key 键名
   * @param {any} defaultValue 默认值
   * @returns {any} 存储的值或默认值
   */
  get(key, defaultValue = null) {
    if (!this.storage) {
      return defaultValue;
    }

    try {
      const storageKey = this.getKey(key);
      const item = this.storage.getItem(storageKey);
      
      if (item === null) {
        return defaultValue;
      }

      return this.deserialize(item);
    } catch (error) {
      console.error('Failed to get sessionStorage item:', error);
      return defaultValue;
    }
  }

  /**
   * 从 sessionStorage 删除值
   * @param {string} key 键名
   */
  remove(key) {
    if (!this.storage) {
      return false;
    }

    try {
      const storageKey = this.getKey(key);
      this.storage.removeItem(storageKey);
      return true;
    } catch (error) {
      console.error('Failed to remove sessionStorage item:', error);
      return false;
    }
  }

  /**
   * 清空所有带前缀的 sessionStorage 项
   */
  clear() {
    if (!this.storage) {
      return false;
    }

    try {
      const keysToRemove = [];
      for (let i = 0; i < this.storage.length; i++) {
        const key = this.storage.key(i);
        if (key && key.startsWith(this.prefix + '_')) {
          keysToRemove.push(key);
        }
      }
      
      keysToRemove.forEach(key => this.storage.removeItem(key));
      return true;
    } catch (error) {
      console.error('Failed to clear sessionStorage:', error);
      return false;
    }
  }

  /**
   * 检查键是否存在
   * @param {string} key 键名
   * @returns {boolean} 是否存在
   */
  has(key) {
    if (!this.storage) {
      return false;
    }

    const storageKey = this.getKey(key);
    return this.storage.getItem(storageKey) !== null;
  }

  /**
   * 获取所有带前缀的键名
   * @returns {Array<string>} 键名数组
   */
  keys() {
    if (!this.storage) {
      return [];
    }

    const keys = [];
    const prefixWithUnderscore = this.prefix + '_';
    
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i);
      if (key && key.startsWith(prefixWithUnderscore)) {
        keys.push(key.substring(prefixWithUnderscore.length));
      }
    }
    
    return keys;
  }

  /**
   * 获取存储大小（字节）
   * @returns {number} 存储大小
   */
  getSize() {
    if (!this.storage) {
      return 0;
    }

    let size = 0;
    const prefixWithUnderscore = this.prefix + '_';
    
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i);
      if (key && key.startsWith(prefixWithUnderscore)) {
        const value = this.storage.getItem(key);
        size += key.length + (value ? value.length : 0);
      }
    }
    
    return size;
  }

  /**
   * 批量设置多个值
   * @param {Object} data 要设置的键值对对象
   * @param {Object} options 选项
   */
  setMultiple(data, options = {}) {
    if (!this.storage || typeof data !== 'object') {
      return false;
    }

    try {
      Object.entries(data).forEach(([key, value]) => {
        this.set(key, value, options);
      });
      return true;
    } catch (error) {
      console.error('Failed to set multiple sessionStorage items:', error);
      return false;
    }
  }

  /**
   * 批量获取多个值
   * @param {Array<string>} keys 要获取的键名数组
   * @param {any} defaultValue 默认值
   * @returns {Object} 键值对对象
   */
  getMultiple(keys, defaultValue = null) {
    if (!Array.isArray(keys)) {
      return {};
    }

    const result = {};
    keys.forEach(key => {
      result[key] = this.get(key, defaultValue);
    });
    
    return result;
  }
}

// 创建默认实例
export const sessStore = new SessionStore();

// 导出类供自定义使用
export { SessionStore };